import { defineNuxtPlugin } from '#app'
import Toast from '~/components/ui/Toast.vue'
import { createApp, h } from 'vue'
import type { ToastOptions, ToastPlugin } from '~/types/toast'

export default defineNuxtPlugin((nuxtApp) => {
  const showToast = (message: string, options: ToastOptions = {}) => {
    const mountNode = document.createElement('div')
    document.body.appendChild(mountNode)

    const app = createApp({
      render() {
        return h(Toast, {
          message,
          type: options.type || 'info',
          position: options.position || 'top-right',
          timeout: options.timeout || 3000,
          showClose: options.showClose !== false,
          ref: 'toast'
        })
      }
    })

    const instance = app.mount(mountNode)
    const toastInstance = instance.$refs.toast as InstanceType<typeof Toast>
    toastInstance?.show()

    setTimeout(() => {
      app.unmount()
      document.body.removeChild(mountNode)
    }, options.timeout || 3000)
  }

  const toast: ToastPlugin = {
    show: showToast,
    success: (message, options) => showToast(message, { ...options, type: 'success' }),
    error: (message, options) => showToast(message, { ...options, type: 'error' }),
    warning: (message, options) => showToast(message, { ...options, type: 'warning' }),
    info: (message, options) => showToast(message, { ...options, type: 'info' })
  }

  return {
    provide: { toast }
  }
  // nuxtApp.provide('toast', toast)


})